from django.shortcuts import render
from web.forms.project import S28
from django.http import JsonResponse
import datetime
import time
import collections


def dashboard(request, project_id):
    """概览展示"""
    # 查询当前项目有多少问题和
    problem_list = S28().py_searche('select statused,count(*) from problem where project_id="{}" group by statused'.format(project_id))
    # 查询当前项目的创建者和参与者
    this_creater = S28().search('user_information', {'id': request.obj[0][6]})
    # 查询最近10条问题作为自己的最新记录
    now_recode = S28().py_searche('select p.the_title,p.start_time,u.user,p.id from problem as p left join user_information as u on p.assign_user_information=u.id order by p.id desc ')[
                 0:10]
    return render(request, 'dashboard.html', {'problem_list': problem_list, 'this_creater': this_creater, 'now_recode': now_recode})


def issues_chart(request, project_id):
    """在概览页面生成highcharts所需的数据"""
    """
        data_list = [
        [1591533701911,9],
        [1591533701911,9],
        [1591533701911,9],
        [1591533701911,9],    
    ]
    返回这样格式的数据就可以了
    :return JsonResponse(data_list)
    
    # 最近30天每天创建的问题数量
    """
    today = datetime.datetime.now().date()
    # 这个sql语句查询到的是近30天的数据
    ret = S28().py_searche('select start_time,DATE_FORMAT(start_time,"%Y-%m-%d"),'
                           'count(*) from problem where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(start_time)'
                           ' GROUP BY start_time')
    # 循环查询结构 把 结果以列表的形式放到li列表里
    li = []
    for i in ret:
        one = datetime.datetime.strftime(i[0], '%Y-%m-%d')
        time_tuple = time.strptime(i[1], '%Y-%m-%d')
        li.append([one,int(time.mktime(time_tuple) * 1000), i[2]])
    """
        循环过后的date_dict字典的格式
        {
        2020-05-06:[111111111,0]
         2020-05-07:[111111111,0]
        }
    """
    # 循环生成30天的有序字典
    date_dict = collections.OrderedDict()
    for i in range(0,30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple())*1000, 0]
    # 判断他们两个之间有没有相同的时间  有的话就用 li 的信息替换 date_dict 的信息
    for i in date_dict:

        for j in li:
            if i == j[0]:
                date_dict[i] = [j[1], j[2]]
    print(date_dict.values())
    return JsonResponse({'status':True, 'data':list(date_dict.values())})


